import React, { ReactElement, useEffect } from "react";
import Layout from "./Layout";
import { Button, Form, Input, Result, message } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/models";
import { AuthState, AUTH_EFFECT } from "@/models/auth";
import { SignupPayload } from "@/models/auth/action";
import { useHistory } from "react-router-dom";
interface Props {}

export default function Signup(props: Props): ReactElement {
  const auth = useSelector<RootState, AuthState>((state) => state.auth);
  const history = useHistory();
  const dispatch = useDispatch();
  const [form] = Form.useForm();

  console.log(auth);
  /**
   *
   * @param payload
   * @description 注册
   */
  const register = async (payload: SignupPayload) => {
    const res = (await dispatch({
      type: AUTH_EFFECT.handleSignup,
      payload,
    })) as any;
    // console.log(222);
    console.log(res);
    // if (res?.status === 200) {
    //   // message.success("注册成功");
    //   // history.push("/signin");
    // } else {
    //   message.error(res);
    // }
  };
  /**
   *
   * @param value
   * @description 点击提交
   */
  const onFinish = (value: SignupPayload) => {
    console.log(value);
    register(value);
  };

  //成功则清空表单
  useEffect(() => {
    if (auth.signup.loaded && auth.signup.success) {
      form.resetFields(); //清空
    }
  }, [auth, form]);
  // 显示成功提示
  const showSuccess = () => {
    if (auth.signup.loaded && auth.signup.success) {
      return (
        <Result
          status="success"
          title="注册成功"
          extra={[
            <Button
              type="primary"
              onClick={() => {
                history.push("/signin");
              }}
            >
              去登录
            </Button>,
          ]}
        />
      );
    }
  };
  const showError = () => {
    if (auth.signup.loaded && !auth.signup.success) {
      return (
        <Result
          status="warning"
          title="注册失败"
          subTitle={auth.signup.message}
        />
      );
    }
  };
  useEffect(() => {
    return () => {
      dispatch({
        type: AUTH_EFFECT.resetSignup,
      });
    };
  }, [dispatch]);

  const signupForm = () => {
    return (
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="name" label="昵称">
          <Input></Input>
        </Form.Item>
        <Form.Item name="password" label="密码">
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item name="email" label="邮箱">
          <Input></Input>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            注册
          </Button>
        </Form.Item>
      </Form>
    );
  };
  return (
    <Layout title="注册" subTitle="还没有账号?注册1个吧.">
      {showSuccess()}
      {showError()}
      {signupForm()}
    </Layout>
  );
}
